import React ,{ useEffect, useState,Fragment } from 'react';
import axios from 'axios';
import logo from './logo.svg'
import './App.css'

// 考题 自定义hooks
// list 每次都去写
// url data => mvvm list
const useHackerNewSApi=()=>{
  const [data,setData]=useState({hits:[]});
  const [isLoading,setIsLoading]=useState(false);
  const [isError,setIsError]=useState(false);
  const [url,setUrl]=useState('https://hn.algolia.com/api/v1/search?query=redux');useEffect(()=>{
    setIsLoading(true);
    const fetchData=async ()=>{
      let result;
      try{ 
        result=await axios(url);
      }
      catch(error){
        setIsError(true);
      }
      // console.log(result);
      setData(result.data);
      setIsLoading(false)
    }
    fetchData();
    // 不监听query 触发频繁 
    // search
    // url
  },[url])
  return [{data,isLoading,isError},setUrl];

}

function App() {
  const [{data,isLoading,isError},setUrl]=useHackerNewSApi();
  // const [count, setCount] = useState(0)
  // const [data,setdata]=useState({hits:[]})
  const [query,setQuery]=useState('redux');
  // const [isError,setIsError]=useState(false);
  // const [search,setSearch]=useState('redux');
  // const [url,setUrl]=useState('https://hn.algolia.com/api/v1/search?query=redux');
  // const [isLoading,setIsLoading]=useState(false);
  // useEffect不只是在mount执行，更新阶段也会执行
  // [] useeffect在什么状态更新后才执行 update 
  
  return (
    <Fragment>
      {/* 性能开销 防抖节流 */}
      <form onSubmit={(e)=>{
          e.preventDefault();
          setUrl(`https://hn.algolia.com/api/v1/search?query=${query}`)
          }}>
        <input type="text" value={query} onChange={event=>setQuery(event.target.value)} />
        <input type="submit" value='search' />
      </form>
      {isError && <div>something error...</div>}
      {isLoading?<div>isLoading...</div>:
      <ul>{
        data.hits.map(item=><li key={item.objectID}>
          <a href={item.url}>{item.title}</a>
        </li>
        )
      }
      </ul>}
    
    </Fragment>
  )
}

export default App
